package com.youoor.interceptors;


import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class RequestAttributeArgumentResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterAnnotation(RequestAttribute.class) != null;
	}

	@SuppressWarnings("unchecked")
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		
		RequestAttribute attr = parameter.getParameterAnnotation(RequestAttribute.class);
		
		if("userId".equals(attr.value())) {
			Object userid = webRequest.getAttribute(attr.value(), WebRequest.SCOPE_REQUEST);
			if(userid != null) {
				return userid;
			}
		}
		
		Object result = null;
		
		Object attribute = webRequest.getAttribute("attributeMap", WebRequest.SCOPE_REQUEST);
		if(attribute!= null && attribute instanceof Map) {
			Map<String,Object> attributeMap = (Map<String,Object>)attribute;
			result =  attributeMap.get(attr.value());
		}
		
		if(result == null)
			result = webRequest.getAttribute(attr.value(), WebRequest.SCOPE_REQUEST);
		
		return result;

		
	}
	
}
